package com.example.springbootsfzy.controller.liujinping;


import com.example.springbootsfzy.util.R;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Paths;
import java.util.UUID;

//@Controller
@RestController
public class VideoController {


    /**
     * 上传视频
     */
    @PostMapping("/video/upload")
    public R upload(@RequestParam("file") MultipartFile[] files) {
        // 获取当前工作目录，确保路径正确
//        String path = Paths.get(System.getProperty("user.dir"), "spring-boot-sfzy","src", "main", "resources", "static", "img").toString();
String path = "E:\\videos";

        // 检查是否有文件上传
        if (files.length == 0) {
            return R.error("上传失败，未选择文件");
        }

        // 确保目标目录存在
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();// 如果目录不存在，创建目录
            System.out.println("当前的路径:" + path);
        }

        // 遍历文件并保存
        for (MultipartFile file : files) {
            String fileName = file.getOriginalFilename();
            if (fileName == null || fileName.isEmpty()) {
                continue;  // 如果文件名为空，则跳过当前文件
            }

            // 获取文件扩展名
            String ext = fileName.substring(fileName.lastIndexOf("."));
            String newFileName = UUID.randomUUID() + ext; // 使用 UUID 生成新文件名

            try {
                // 保存文件到指定路径
                file.transferTo(new File(path + File.separator + newFileName));
            } catch (IOException e) {
                // 如果保存文件失败，返回上传失败的信息
                return R.error("上传失败：" + e.getMessage());
            }
        }

        // 返回成功信息
        return R.ok("上传成功");
    }



    @GetMapping("/video/stream")
    public void streamVideo(HttpServletRequest request, HttpServletResponse response) {
        //M:\1_3.mp4
        String videoPath = "D:\\1.mp4"; // 视频文件路径
        BufferedInputStream inputStream=null;
        OutputStream os=null;
        try {
            File videoFile = new File(videoPath);
            long contentLength = videoFile.length();

            response.setContentType("video/mp4");
            response.setHeader("Content-Disposition", "attachment; filename=\"video.mp4\"");
            response.setHeader("Content-Length", String.valueOf(contentLength));

            // 使用BufferedInputStream提高读取效率
            inputStream= new BufferedInputStream(new FileInputStream(videoFile));
            os= response.getOutputStream();

            // 创建缓冲区
            byte[] buffer = new byte[4096]; // 可以根据需要调整缓冲区大小
            int bytesRead;

            // 循环读取数据并写入响应输出流
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);
                os.flush(); // 确保数据即时发送
            }

            os.close();
            inputStream.close();
        } catch (Exception e) {
            System.out.println("关闭连接");
        }finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                System.out.println("Error closing streams: " + e.getMessage());
            }
        }
    }
//    @GetMapping("/video/stream.m3u8")
//    public void streamVideoM3U8(HttpServletRequest request, HttpServletResponse response) {
//        response.setContentType("application/vnd.apple.mpegurl");
//        response.setHeader("Content-Disposition", "inline; filename=\"stream.m3u8\"");
//
//        try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(response.getOutputStream()))) {
//            // 写入M3U8播放列表内容
//            writer.write("#EXTM3U\n");
//            writer.write("#EXT-X-VERSION:3\n");
//            writer.write("#EXT-X-TARGETDURATION:10\n");
//            writer.write("#EXTINF:10, nodesc\n");
//            writer.write("stream.ts\n");
//            // 继续添加其他TS文件
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
}